package com.xindacloud.sms.portal.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xindacloud.sms.portal.dao.SmsSubmissionRecordMapper;
import com.xindacloud.sms.portal.dto.SearchMessageDTO;
import com.xindacloud.sms.portal.entity.SmsAgent;
import com.xindacloud.sms.portal.entity.SmsSubmissionRecord;
import com.xindacloud.sms.portal.exception.ServiceException;
import com.xindacloud.sms.portal.service.ISmsAgentService;
import com.xindacloud.sms.portal.service.ISmsSubmissionRecordService;
import com.xindacloud.sms.portal.utils.UnionResultHelp;
import com.xindacloud.sms.portal.vo.SearchMessageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SmsSubmissionRecordServiceImpl extends ServiceImpl<SmsSubmissionRecordMapper, SmsSubmissionRecord> implements ISmsSubmissionRecordService {

    private final CommonServiceImpl commonService;

    private final ISmsAgentService smsAgentService;

    @Autowired
    public SmsSubmissionRecordServiceImpl(CommonServiceImpl commonService, ISmsAgentService smsAgentService) {
        this.commonService = commonService;
        this.smsAgentService = smsAgentService;
    }

    @Override
    public IPage<SearchMessageVO> searchMessage(SearchMessageDTO searchMessageDTO) {

        final int userId;
        try {
            userId = Integer.parseInt(searchMessageDTO.getUserId());
        } catch (NumberFormatException e) {
            throw new ServiceException("无效的用户ID", UnionResultHelp.StatusEnum.ParamsFail.code());
        }

        List<Integer> userIds = commonService.queryUserIdsFor(userId);
        if (CollectionUtils.isEmpty(userIds)) {
            return null;
        }

        final String messageIds = searchMessageDTO.getMessageIds();
        List<String> messageIdList = null;
        if (StringUtils.isNotEmpty(messageIds)) {
            messageIdList = Arrays.asList(messageIds.split(","));
        }

        final IPage<SmsSubmissionRecord> smsSubmissionRecordIPage = lambdaQuery()
                .in(CollectionUtils.isNotEmpty(messageIdList),
                        SmsSubmissionRecord::getMessageId, messageIdList)
                .in(CollectionUtils.isNotEmpty(userIds),
                        SmsSubmissionRecord::getUserId, userIds)
                .or(StringUtils.isNotEmpty(searchMessageDTO.getTo()), queryWrapper ->
                        queryWrapper.eq(SmsSubmissionRecord::getSendTo, searchMessageDTO.getTo()))
                .or(StringUtils.isNotEmpty(searchMessageDTO.getTo()), queryWrapper ->
                        queryWrapper.eq(SmsSubmissionRecord::getSendTo, "00".concat(searchMessageDTO.getTo())))
                .eq(StringUtils.isNotEmpty(searchMessageDTO.getAgentId()),
                        SmsSubmissionRecord::getAgentId, searchMessageDTO.getAgentId())

                .ge(StringUtils.isNotEmpty(searchMessageDTO.getStartDate()), SmsSubmissionRecord::getSubmitTime,
                        searchMessageDTO.getStartDate().concat(" ").concat("00:00:00"))
                .le(StringUtils.isNotEmpty(searchMessageDTO.getEndDate()), SmsSubmissionRecord::getSubmitTime,
                        searchMessageDTO.getEndDate().concat(" ").concat("23:59:59"))
                .orderByDesc(SmsSubmissionRecord::getSubmitTime)
                .page(new Page<>(searchMessageDTO.getCurrentPage(), searchMessageDTO.getPageSize()));

        final Map<String, SmsAgent> agentMap = smsAgentService.queryAllAgent()
                .stream()
                .collect(Collectors.toMap(SmsAgent::getAgentId, Function.identity(), (key1, key2) -> key2));

        return smsSubmissionRecordIPage.convert(smsSubmissionRecord -> {
            SearchMessageVO searchMessageVO = new SearchMessageVO();
            BeanUtils.copyProperties(smsSubmissionRecord, searchMessageVO);
            searchMessageVO.setAgentName(getAgentName(agentMap, smsSubmissionRecord));
            return searchMessageVO;
        });

    }

    private String getAgentName(Map<String, SmsAgent> agentMap, SmsSubmissionRecord smsSubmissionRecord) {
        if (CollectionUtils.isNotEmpty(agentMap)) {
            final SmsAgent smsAgent = agentMap.get(smsSubmissionRecord.getAgentId());
            if (Objects.nonNull(smsAgent)) {
                return smsAgent.getAgentName();
            }
        }
        return "Unknown";

    }
}
